# app/main.py
import logging
from logging.config import fileConfig
import redis
import socketio
import uvicorn
from fastapi import FastAPI, Depends
from fastapi.security import HTTPBearer
from core.config import settings
from core.database import Base, engine
from core.dependencies import get_sio
# from core.init_db import init_db

from routers import (router, adapter_router, users, friends_router, message_router, mq_router,qw_router,
                     image_router, sms_router,customers, official,voice_router,rag_router,call_tasks_router,templates_router)


fileConfig("logging.conf")
logger = logging.getLogger("app")

from db.mysql.users import Users
from db.mysql.customers import Customers
from db.mysql.customer_platform import CustomerPlatform
from db.mysql.official_contact import OfficialContact
# 创建mysql

# 只有在引擎存在时才创建表
if engine is not None:
    Base.metadata.create_all(bind=engine)

# '''

# 创建 Socket.IO 异步服务器
sio = get_sio()
socket_app = socketio.ASGIApp(sio)

# 导入 Socket.IO 服务（这会注册事件处理器）
from services import sio_service
# 创建 FastAPI 实例
app = FastAPI(title="My FastAPI App")
# 在应用启动时创建连接池
security = HTTPBearer()
app.mount("/socket.io", socket_app)
# 包含路由
app.include_router(adapter_router.router)
app.include_router(templates_router.router)
app.include_router(router.router)
app.include_router(users.router)
app.include_router(friends_router.router)
app.include_router(message_router.router)
app.include_router(customers.router)
# app.include_router(webhook_router.router)
app.include_router(mq_router.router)
app.include_router(call_tasks_router.router)
app.include_router(official.router)
app.include_router(qw_router.router)
app.include_router(voice_router.router)
app.include_router(sms_router.router)
app.include_router(image_router.router)
app.include_router(rag_router.router)

# 初始化数据库连接
# app.add_event_handler("startup", init_db)

@app.get("/test-403")
async def test_403():
    logger.info("test 403")
    return {"message": "应该正常工作"}

@app.get("/test-auth")
async def test_auth(credentials=Depends(security)):
    return {"message": "需要认证"}

@app.get("/test-redis")
def test_redis():
    r = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=0, decode_responses=True)
    r.set("test", "123")
    return {"message": "ok"}



if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000,reload=False,workers=1)